<?php

/*
 * yangzhic
 * 2016年8月17日下午6:50
 * OrderController
 */
namespace SDXApi\Controller;

use Think\Controller;
use Think\Model;
Vendor('alipush.aliyun-php-sdk-core.Config');
use \Push\Request\V20150827 as Push;

class MarketingPushController extends Controller {
	
	/*
     * 查询推送状态
     */
    public function check_push(){
        $push_list=M("message_log")->alias("ml")->join("left join sdx_mail_templates as mt on mt.template_id=ml.templates_id")->field("ml.message_id,ml.android_state,ml.ios_state,ml.state,ml.user_id,mt.push_title,mt.click_push_notify_type,mt.ios_activity,mt.ios_param_key,mt.ios_param_val,mt.android_activity,mt.android_param_key,mt.android_param_val,mt.click_push_title,mt.click_push_web_title,mt.click_push_web_title,mt.click_push_act,mt.template_id,mt.message_id as mid,mt.template_content,mt.push_status,mt.sms_count,mt.sms_finish,mt.android_count,mt.android_finish,mt.ios_count,mt.ios_finish,ml.con_phone")->where(array('ml.template_type'=>1,'_string'=>'(state=4 or android_state=4 or ios_state=4) and (mt.is_timing=0 or mt.is_timing=1 and mt.execution_time<'.time().')'))->limit(1000)->select();
        $message_arr=array();
        $message_content=array();
        foreach($push_list as $item){
            
            if($item['push_status']==0){
                M("mail_templates")->where(array('template_id'=>$item['template_id']))->save(array('push_status'=>1));
            }
           
            $android_finish=$item['android_finish'];
            $ios_finish=$item['ios_finish'];
            $sms_finish=$item['sms_finish'];
            
            
        $ExtParameters=array(
                'ios'=>array('type'=>$item['ios_activity'],'parameter'=>array()),
                'android'=>array('activity'=>str_replace(" ","",$item['android_activity']),'parameter'=>array())
            );
            if(!empty($item['ios_param_key']) && !empty($item['ios_param_val'])){
                $ios_param_key=$item['ios_param_key'];
                $ios_param_val=$item['ios_param_val'];
                $ExtParameters['ios']['parameter'][$ios_param_key]=$ios_param_val;
            }
            
            if(!empty($item['android_param_key']) && !empty($item['android_param_val'])){
                $android_param_key=$item['android_param_key'];
                $android_param_val=$item['android_param_val'];
                $ExtParameters['android']['parameter'][$android_param_key]=$android_param_val;
                
            }
            
            if($item['click_push_title']=='3'){
                $ExtParameters['android']['activity']='com.weechan.shidexianapp.activity.WebActivity';
                $ExtParameters['android']['parameter']['INTENT_TITLE']=$item['click_push_web_title'];
                $ExtParameters['android']['parameter']['com.weechan.shidexianapp']=$item['click_push_act'];
                
                $ExtParameters['ios']['type']='web';
                $ExtParameters['ios']['parameter']['web_title']=$item['click_push_web_title'];
                $ExtParameters['ios']['parameter']['web_url']=$item['click_push_act'];
            }
            
            
            if(!empty($item['click_push_notify_type'])){
                $ExtParameters['android']['parameter']['_NOTIFY_TYPE_']=$item['click_push_notify_type'];
            }

            
            
            if($item['android_state']=='4'){
                $device_sn_list=M("alipush")->field("device_sn")->where(array('user_id'=>$item['user_id'],'device_type'=>'Android'))->order('add_time desc')->limit(1)->select();
                
                
                
                $device_sn=array();
                foreach($device_sn_list as $li){
                    $device_sn[]=$li['device_sn'];
                }
                if(!empty($device_sn)){
                    $response=$this->alipush($device_sn, $item['push_title'], $item['template_content'],$ExtParameters,$item['click_push_title'],'Android');
                   
                    if(!$response->ResponseId){
                        $this->update_message_log($item['message_id'],'android_state', 0);
                    }else{
                        $this->update_message_log($item['message_id'],'android_state', 2,$response->ResponseId);
                    }
                    M("mail_templates")->where(array('template_id'=>$item['template_id']))->setInc("android_effective");
                }else{
                    $this->update_message_log($item['message_id'],'android_state', 3);
                }
                
                M("mail_templates")->where(array('template_id'=>$item['template_id']))->setInc("android_finish");
                
                $android_finish++;
            }
            
            
            
            if($item['ios_state']=='4'){
                
                $device_sn_list=M("alipush")->field("device_sn")->where(array('user_id'=>$item['user_id'],'device_type'=>'Ios'))->order('add_time desc')->limit(1)->select();
                $device_sn=array();
                foreach($device_sn_list as $li){
                    $device_sn[]=$li['device_sn'];
                }
                if(!empty($device_sn)){
                    
                    $response=$this->alipush($device_sn, $item['push_title'], $item['template_content'],$ExtParameters,$item['click_push_title'],'Ios');
                     
                    if(!$response->ResponseId){
                        $this->update_message_log($item['message_id'],'ios_state', 0);
                    }else{
                        $this->update_message_log($item['message_id'],'ios_state', 2,$response->ResponseId);
                    }
                    M("mail_templates")->where(array('template_id'=>$item['template_id']))->setInc("ios_effective");
                }else{
                    $this->update_message_log($item['message_id'],'ios_state', 3);
                }
                M("mail_templates")->where(array('template_id'=>$item['template_id']))->setInc("ios_finish");
                
                $ios_finish++;
            }
            
            if($item['state']=='4'){
                
                
                if(!empty($item['con_phone'])){
                    //$phoneArr[]=$item['con_phone'];
                    //$send_data = $this->send_message_api_netease($item['mid'],$item['con_phone'],array());
                    
                    if(in_array($item['template_content'],$message_content)){
                        
                        foreach($message_arr as $message_item){
                            if($item['template_content']==$message_item['template_content']){
                                $message_item['con_phone'].=','.$item['con_phone'];
                            }
                        }
                    }else{
                        
                        $message_content[]=$item['template_content'];
                        $message_arr[]=array('template_content'=>$item['template_content'],'con_phone'=>$item['con_phone']);
                    }
                    
                    
                    
                    //$send_data=$this->pushMess($item['con_phone'],$item['template_content']);
                    $this->update_message_log($item['message_id'],'state', 1);
    
                    /* if($send_data=='0'){
                        $this->update_message_log($item['message_id'],'state', 1);
                    }else{
                        $this->update_message_log($item['message_id'],'state', 0);
                    } */
                    
                    M("mail_templates")->where(array('template_id'=>$item['template_id']))->setInc("sms_effective");
                    
                }else{
                    $this->update_message_log($item['message_id'],'state', 3);
                }
                M("mail_templates")->where(array('template_id'=>$item['template_id']))->setInc("sms_finish");
                
                $sms_finish++;
            }
            
            
            if($item['android_count']>=$android_finish && $item['ios_count']>=$ios_finish && $item['sms_count']>=$sms_finish){
                
                M("mail_templates")->where(array('template_id'=>$item['template_id']))->save(array('push_status'=>2));
            }
            
            
        }
        
        
        
        
        foreach($message_arr as $item){
            $a = new qybsms();
            $resultObj = $a->sendMessage($item['con_phone'],$item['template_content'].'【食得鲜】');
        }
        
        
        echo 'Success';
    }
    

    private function alipush($device_sn,$title,$body,$ExtParameters=array(),$OpenType=1,$device_type){
        $title=mb_substr($title,0,20,'utf-8');
        // 设置你自己的AccessKeyId/AccessSecret/AppKey
        $accessKeyId = C("ALIPUSH_ACCESSKEYID");
        $accessSecret = C("ALIPUSH_ACCESSSECRET");
        $appKey = C("ALIPUSH_APPKEY");
    
        $iClientProfile = DefaultProfile::getProfile("cn-hangzhou", $accessKeyId, $accessSecret);
    
        $client = new DefaultAcsClient($iClientProfile);
        $request = new Push\PushRequest();
    
        // 推送目标
        $request->setAppKey($appKey);
        $request->setTarget("device"); //推送目标: device:推送给设备; account:推送给指定帐号,tag:推送给自定义标签; all: 推送给全部
        $request->setTargetValue(implode(",",$device_sn)); //根据Target来设定，如Target=device, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
        $request->setDeviceType(3); // 设备类型deviceType 取值范围为:0~3. iOS设备: 0; Android设备: 1; 全部: 3, 这是默认值.
    
        // 推送配置
        $request->setType(1); // 0:表示消息(默认为0), 1:表示通知
        $request->setTitle($title); // 消息的标题
        if($device_type=='Ios'){
            $request->setBody(" "); // 消息的内容
        }else{
            $request->setBody($body); // 消息的内容
        }
        $request->setSummary($body); // 通知的摘要
    
    
        // 推送配置: iOS
        $request->setiOSBadge("5"); // iOS应用图标右上角角标
        $request->setiOSMusic("default"); // iOS通知声音
        $request->setiOSTitle($title);//iOS通知标题(iOS 10+)
        //$request->setiOSSubtitle($body);//iOS通知副标题(iOS 10+)
        $request->setiOSMutableContent("true");//使能通知扩展处理(iOS 10+)
        $request->setiOSNotificationCategory("test_category");//设定通知Category(iOS 10+)
        if(!empty($ExtParameters['ios'])){
            $request->setiOSExtParameters(json_encode($ExtParameters['ios'])); //自定义的kv结构,开发者扩展用 针对iOS设备（iOS 10+可以使用attachment关键字来指定富媒体推送通知的资源Url）
        }
        $request->setApnsEnv("PRODUCT");
        $request->setRemind("true"); // 推送时设备不在线（既与移动推送的服务端的长连接通道不通），则这条推送会做为通知，通过苹果的APNs通道送达一次(发送通知时,Summary为通知的内容,Message不起作用)。注意：离线消息转通知仅适用于生产环境
    
        // 推送配置: Android
        if($OpenType!='1'){
            $OpenType='2';
        }
        $request->setAndroidOpenType($OpenType); // 点击通知后动作,1:打开应用 2: 打开应用Activity 3:打开 url 4 : 无跳转逻辑
        //$request->setAndroidOpenUrl($url); // Android收到推送后打开对应的url,仅仅当androidOpenType=3有效
        $request->setAndroidActivity($ExtParameters['android']['activity']);
        //$request->setsetXiaomiActivity("_Your_XiaoMi_Activity_");//设置该参数后启动小米托管弹窗功能，此处指定通知点击后跳转的Activity（托管弹窗的前提条件：1. 继承小米辅助通道；2. storeOffline设为true)
         
        if(!empty($ExtParameters['android']['parameter'])){
            $request->setAndroidExtParameters(json_encode($ExtParameters['android']['parameter'])); //设定android类型设备通知的扩展属性
        }
    
        // 推送控制
        $pushTime = gmdate('Y-m-d\TH:i:s\Z', strtotime('+3 second'));//延迟3秒发送
        $request->setPushTime($pushTime);
        $expireTime = gmdate('Y-m-d\TH:i:s\Z', strtotime('+1 day'));//设置失效时间为1天
        $request->setExpireTime($expireTime);
        $request->setTimeOut(3); 
        $request->setStoreOffline("true"); // 离线消息是否保存,若保存, 在推送时候，用户即使不在线，下一次上线则会收到
    
        $response = $client->getAcsResponse($request);
    
        return $response;
    }

    
    private function pushMess($con_phone,$content){
        $url='http://ip/msg/HttpSendSM';
        $ch = curl_init();
        $timeout = 20;
        /** 有些curl版本的post这样的数据格式 **/
        //$post_data = "account=账号&pswd=密码&mobile=手机号码1,号码2,号码3,后面以此类推&msg=您好,你的验证码:8888【巨辰科技】&needstatus=true&product=";

         $post_data = array(
         "account"=>"cryouguo",
         "pswd"=>"168168",
         "mobile"=>$con_phone,
         "msg"=>$content,
         "needstatus"=>"true",
         "product"=>''
         );

        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        //post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        return $file_contents;
    }
    
    private function send_message_api_netease($template_id=null,$phone=array(),$param=array()){
        //return true;
        //网易云信短信发送测试
        //$phone = array("15820245055");
        //$param = array("name",'order_sn');
        //网易云信短信发送测试
        if (!empty($template_id)||!empty($phone)||!empty($param)){
            $data_mobile = json_encode($phone);
            $data_params = json_encode($param);
            $res = $this->requst($template_id,$data_mobile,$data_params);
            $send_re = json_decode($res,true);
    
            if($send_re['code']==200){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
        //dump($html);
    }
    
    private function  update_message_log($message_id, $state_field,$state,$alimsg_id=0){
        if(!empty($state_field) && !empty($state)){
            $message_logw['message_id'] = $message_id;
            $message_log[$state_field] = $state;
            if($alimsg_id!=0){
                $message_log['alimsg_id'] = $alimsg_id;
            }
    
            M("message_log")->where($message_logw)->save($message_log);
        }
    }
    
    private function requst($templateid,$mobiles,$params){
        $appKey = C("AppKey");
        $appSecret = C("AppSecret");
        $nonce = rand(100000,999999);
        $curTime = time();
        $checkSum = sha1($appSecret . $nonce . $curTime);
        $opts = array (
            'http' => array(
                'method' => 'POST',
                'header' => array(
                    'Content-Type:application/x-www-form-urlencoded;charset=utf-8',
                    "AppKey:$appKey",
                    "Nonce:$nonce",
                    "CurTime:$curTime",
                    "CheckSum:$checkSum"
                ),
                'content' =>  'templateid='.$templateid.'&mobiles='.$mobiles.'&params='.$params
            ),
        );
        //return $opts;
        $context = stream_context_create($opts);
        $html = file_get_contents(C('NETEASE_API_URL'), false, $context);
        //w_log("log",$html);
        return $html;
    }
	
}

class qybsms{
    var $username = "youguo01"; //在这里配置你们的发送帐号
    var $passwd = "168168";    //在这里配置你们的发送密

    /**
     **发送短信函数
     **$phone 为手机号码，可以一个或多个号码，多个号码以“,”号隔开 例：13800000000,13800000000
     **$msg 为短信内容，请发正规的验证码或行业通知类的内容和带签名,测试用例请发："你好，你的验证码为：666888.【微软科技】"
     **$sendtime 为发送时间，为空立即发送，时间格式为："2016-12-12 12:12:12"
     **$port 为端口号，默认为空
     **$needstatus 是否需要状态回推,值为true或false,回推地址在后台设置
     **所有线上公开促发短信发送的接入，比如公开的验证码、注册等必须加以判断每个号码的发送限制、ip发送短信限制
     **/
    function sendMessage($phone,$msg,$sendtime='',$port='',$needstatus=''){
        $ch = curl_init();
        $post_data = "username=".$this->username."&passwd=".$this->passwd."&phone=".$phone."&msg=".urlencode($msg)."&needstatus=true&port=".$port."&sendtime=".$sendtime;
        /**
         php5.4或php6 curl版本的curl数据格式为数组   你们接入时要注意
         $post_data = array(
         "username"="账号",
         "passwd"="密码",
         "mobile"="手机号码1,号码2,号码3".
         "msg"="您好,你的验证码:8888【企业宝】",
         "needstatus"="true",
         "port"='',
         "sendtime"=''
         );
         **/
        curl_setopt ($ch, CURLOPT_URL,"http://www.qybor.com:8500/shortMessage");
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        return json_decode($file_contents);
    }
}